<?php

namespace app\api\controller\app;

use app\admin\model\Banner;
use app\admin\model\City;
use app\admin\model\Org;
use app\admin\model\OrgIndexNotice;
use app\admin\model\OrgNotice;
use app\admin\model\Roomclean;
use app\admin\model\Shop;
use app\admin\model\Shopallcharge;
use app\admin\model\Shopallchargeorder;
use app\admin\model\Shopdevice;
use app\admin\model\Shopmno;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Shoptableorder;
use app\admin\model\Userallbalance;
use app\admin\model\Userbalance;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\api\service\DeviceService;
use app\api\service\KsService;
use app\api\service\MtService;
use app\api\service\MtUtil;
use app\api\service\VbillService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Config;
use think\Validate;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 */
class Charge extends Api
{
    protected $noNeedLogin = ['callback','getList'];
    protected $noNeedRight = '*';

    public function getList()
    {
        $shopAllChargeModel = new Shopallcharge();
        $shop_id = $this->request->param('shop_id');
        $user = $this->auth->getUser();

        $list = $shopAllChargeModel->order('amount','asc')->select();


        $userBalanceModel = new Userbalance();
        $totalAmount = $userBalanceModel->balance($shop_id,$user['id']);

        $userAllBalanceModel = new Userallbalance();
        $allBalance = $userAllBalanceModel->userBalance($user['id']);
        $shopBalance = formatMoney($totalAmount);

        $ret= array();
        $ret['list'] = $list;
        $ret['balance'] = formatMoney($shopBalance+$allBalance);
        $ret['shopBalance'] = $shopBalance;//店铺余额
        $ret['allBalance'] = $allBalance;//平台余额


        $this->success('',$ret);

    }


    public function addOrder()
    {
        $id = $this->request->param('id');
        $shop_id = $this->request->param('shop_id');
        $shopAllChargeModel = new Shopallcharge();
        $charge = $shopAllChargeModel->where('id',$id)->find();
        if(!$charge)$this->error("充值套餐不存在");

        $user = $this->auth->getUser();
        $db = array();
        $orderNo = getOrderSn();
        $db['user_id'] = $user['id'];
        $db['order_no'] = $orderNo;
        $db['amount'] = $charge['amount'];
        $db['status'] = 'paying';
        $db['shop_id'] = $shop_id;
        $db['charge_id'] = $id;
        $db['create_time'] = time();
        $db['get_amount'] = $charge['get_amount'];
        $db['org_id'] = 27;
        $db['mark'] = "";

        $shopAllChargeOrderModel = new Shopallchargeorder();
        $orderId = $shopAllChargeOrderModel->insertGetId($db);
        if($orderId){

            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/charge/callback";

            $userWxModel = new Userweixin();
            $wx = $userWxModel->where('user_id',$user['id'])->find();
            $req['mno'] = "399250109386123";
            $req['ordNo'] = $orderNo;
            $req['amt'] = formatMoney($charge['amount']);

            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";
            $req['subAppid'] = "wx4abd56997bacbaee";
            $req['userId'] = $wx['openid'];

            $req['subject'] = "平台余额充值";
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;


            $vbillService = new VbillService();
            $res = $vbillService->jsApi($req);
            $result = json_decode($res, true);
            $bizCode = $result['respData']['bizCode'];
            $bizMsg = $result['respData']['bizMsg'];

            if ($bizCode == '0000') {
                $info['order_no'] = $orderNo;
                $info['payInfo'] = $result['respData'];

                $this->success('',$info);
            } else {
                $this->error($bizMsg);
            }
        }else{
            $this->error("充值失败");
        }

    }
    public function callback()
    {
        $param = file_get_contents("php://input");

        $ret = json_decode($param, true);
        $amt = $ret['amt'];
        $out_trade_no = $ret['ordNo'];
        $transactionId = $ret['transactionId'];
        if ($ret['bizCode'] == '0000') {

            $back = array();
            $back['code'] = "success";
            $back['msg'] = "成功";
            echo json_encode($back);

            $shopAllChargeOrderModel = new Shopallchargeorder();
            $order = $shopAllChargeOrderModel->where('order_no',$out_trade_no)->find();
            $shopAllChargeOrderModel->where('id',$order['id'])->update(['status'=>'payed']);

            $ratio = $order['get_amount']/$order['amount'];
            $userAllBalanceModel = new Userallbalance();
            $userAllBalanceModel->insert(['ratio'=>$ratio,'shop_profit'=>$order['amount'],'user_id'=>$order['user_id'],'type'=>'in','amount'=>$order['get_amount'],'create_time'=>time(),'from'=>'charge','order_id'=>$order['id']]);
        }
    }


    public function getBalanceList()
    {

        $type = $this->request->param('type');
        $page = $this->request->param('page');

        $limit = 10;
        $offset = ($page - 1) * $limit;

        $where = array();
        if($type != ''){
            if($type == 'out'){
                $where['type'] = "out";
            }else{
                $where['type'] = "in";
            }
        }

        $user = $this->auth->getUser();
        $userAllBalanceModel = new Userallbalance();
        $list = $userAllBalanceModel->where($where)->where('user_id',$user['id'])->order('create_time','desc')->limit($offset,$limit)->select();
        $shopOrderModel = new Shoporder();
        $tableOrderModel = new Shoptableorder();
        foreach ($list as $key=>$val){
            $list[$key]['shop'] = "";
            $list[$key]['room'] = "";
            if($val['type'] == 'in'){
                $list[$key]['amount'] = "+".$val['amount'];
                if($val['from'] == 'charge'){
                    $list[$key]['type_txt'] = "余额充值";
                }else if($val['from'] == 'send'){
                    $list[$key]['type_txt'] = "余额转赠";
                }else{
                    $list[$key]['type_txt'] = "收入";
                }
            }else{
                if($val['from'] == 'order'){
                    if($val['order_type'] == 'tq'){
                       $order =  $tableOrderModel->where('id',$val['order_id'])->find();
                       $list[$key]['type_txt'] = $order['shop_name']."_".$order['table_name']."抵扣";
                    }else{
                       $order =  $shopOrderModel->where('id',$val['order_id'])->find();
                       $list[$key]['type_txt'] = $order['shop_name']."_".$order['room_name']."抵扣";

                    }
                }
                $list[$key]['type_text'] = "支出";
                $list[$key]['amount'] = "-".$val['amount'];

            }
            $list[$key]['create_time_text'] = date("Y-m-d",$val['create_time']);

        }
        $this->success('',$list);
    }




}
